//
//  AZMainViewController.m
//  AZBLE
//
//  Created by AZ-Mac on 2017/4/28.
//  Copyright © 2017年 AZ-Mac. All rights reserved.

#import "AZMainViewController.h"
#import "BLETool.h"
#import "AZPeripheralCell.h"
#import "AZPeripheralModel.h"
//#import "AZSettingViewController.h"
#import "AZPeripheralViewController.h"
#import "AZProgressHUD.h"
#import <MJRefresh.h>
#import "AZTestViewController.h"
@interface AZMainViewController () <CBCentralManagerDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *peripheralsTableView;
/** ble */
@property(strong,nonatomic) BLETool *ble;
/** 外设 */
@property(strong,nonatomic) NSMutableArray *peripherals;
@end

@implementation AZMainViewController

static NSString *peripheralCell = @"PeripheralCell";

- (NSMutableArray *)peripherals
{
    if(!_peripherals)
    {
        _peripherals = [NSMutableArray array];
    }
    return _peripherals;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.ble.cMgr.delegate = self;
    [self.peripheralsTableView.mj_header beginRefreshing];
    
}
- (void)initUI
{
    self.view.backgroundColor = [UIColor colorWithRed:(10/255) green:(10/255) blue:(10/255) alpha:0.1];
    self.view.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
    self.view.backgroundColor = AZCommonBgColor;
    //初始化蓝牙
    self.ble =  [[BLETool alloc]init];
    [self.ble initWithDelegate:self queue:dispatch_queue_create("BLEQuene",DISPATCH_QUEUE_CONCURRENT)];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"蓝牙助手";
    
    UIButton * refreshButton = [[UIButton alloc]init];
    [refreshButton setImage:[UIImage imageNamed:@"refreshImage"] forState:UIControlStateNormal];
    refreshButton.backgroundColor = [UIColor redColor];
    refreshButton.frame = CGRectMake(0, 0, 50, 50);
    [refreshButton addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:refreshButton];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(scanForPeripheral)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"MainTagSubIcon"] style:UIBarButtonItemStylePlain target:nil action:nil];
    
    self.peripheralsTableView.backgroundColor = AZCommonBgColor
    self.peripheralsTableView.delegate = self;
    self.peripheralsTableView.dataSource = self;
    self.peripheralsTableView.rowHeight = 80 ;
    self.peripheralsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.peripheralsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(scanForPeripheral)];
    [self.peripheralsTableView registerNib:[UINib nibWithNibName:@"AZPeripheralCell" bundle:nil] forCellReuseIdentifier:peripheralCell];

}
- (void)rightClick
{
    AZTestViewController *testVc = [AZTestViewController new];
    [self.navigationController pushViewController:testVc animated:YES];
}
- (void)scanForPeripheral
{
    [self.peripherals removeAllObjects];
    [self.ble.cMgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripheralsTableView reloadData];

    [self.peripheralsTableView.mj_header endRefreshing];
}
#pragma mark - tableViewDelegate -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.peripherals.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AZPeripheralCell *cell = [tableView dequeueReusableCellWithIdentifier:peripheralCell];
    cell.peripheralModel = self.peripherals[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    AZPeripheralViewController *peripheralVc =  [[AZPeripheralViewController alloc]init];
    AZPeripheralModel *model =  self.peripherals[indexPath.row];
    [AZProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@">>>开始连接（%@）的设备",model.peripheral.name]];
    peripheralVc.currPeripheral = model.peripheral;
    [self.navigationController pushViewController:peripheralVc animated:YES];
}
#pragma mark - CBCentralManagerDelegate -
/*
 * 发现蓝牙设备
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
//    NSLog(@"+++++++++++++++++++++++peripheral.name:%@ + per外设为 = %@,services.count: %lu data = %@,+ rssi信号强度 = %@++++++++++++++++++++++++",peripheral.name,peripheral,peripheral.services.count, advertisementData, RSSI);
    
    [self.peripherals addObject:[AZPeripheralModel modelWithCBPeripheral:peripheral RSSI:RSSI]];
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.peripheralsTableView reloadData];
    });
}
// 中心管理者状态改变, 在初始化CBCentralManager的时候会打开设备，只有当设备正确打开后才能使用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
//    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
        {
//            NSLog(@">>>CBCentralManagerStatePoweredOff");
//            
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"蓝牙未开启" message:@"请开启蓝牙" preferredStyle:UIAlertControllerStyleAlert];
//            [alert addAction:[UIAlertAction actionWithTitle:@"开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                NSURL *url = [NSURL URLWithString:@"prefs:root=Bluetooth"];
//                if ([[UIApplication sharedApplication] canOpenURL:url])
//                {
//                    [[UIApplication sharedApplication] openURL:url];
//                }
//                
//            }]];
//            
//            [alert addAction:[UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [AZProgressHUD showInfoWithStatus:@"蓝牙开启失败"];
//            }]];
//
//            [self presentViewController:alert animated:YES completion:nil];
//            [AZProgressHUD s:@"请开启蓝牙"];
        }
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@"StatePoweredOn点击开始搜索设备");
            break;
        default:
            break;
    }
}
@end
